const { DataTypes } = require('sequelize');
const bcrypt = require('bcryptjs');

module.exports = (sequelize) => {
  const User = sequelize.define('User', {
  id: {
    type: DataTypes.BIGINT.UNSIGNED,
    primaryKey: true,
    autoIncrement: true
  },
  phone: {
    type: DataTypes.STRING(20),
    allowNull: true
  },
  password: {
    type: DataTypes.STRING,
    allowNull: true
  },
  nickname: {
    type: DataTypes.STRING,
    allowNull: true
  },
  avatar: {
    type: DataTypes.STRING,
    allowNull: true
  },
  gender: {
    type: DataTypes.ENUM('male', 'female', 'unknown'),
    defaultValue: 'unknown'
  },
  birthday: {
    type: DataTypes.DATE,
    allowNull: true
  },
  points: {
    type: DataTypes.DECIMAL(10, 2),
    defaultValue: 0.00
  },
  memberLevel: {
    type: DataTypes.STRING,
    defaultValue: 'bronze',
    field: 'member_level'
  },
  invitationCode: {
    type: DataTypes.STRING(20),
    allowNull: true,
    field: 'invitation_code'
  },
  inviterId: {
    type: DataTypes.BIGINT.UNSIGNED,
    allowNull: true,
    field: 'inviter_id',
    references: {
      model: 'users',
      key: 'id'
    }
  },
  role: {
    type: DataTypes.STRING,
    defaultValue: 'user',
    comment: '用户角色：admin, user'
  },
  status: {
    type: DataTypes.INTEGER,
    defaultValue: 1,
    comment: '1:正常 0:禁用'
  },
  lastLogin: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'last_login'
  },
  wechatOpenid: {
    type: DataTypes.STRING,
    allowNull: true,
    field: 'wechat_openid'
  },
  wechatUnionid: {
    type: DataTypes.STRING,
    allowNull: true,
    field: 'wechat_unionid'
  }
}, {
  tableName: 'users',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  hooks: {
    beforeCreate: async (user) => {
      // 加密密码
      if (user.password) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
      
      // 生成邀请码
      if (!user.invitationCode) {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let code = '';
        for (let i = 0; i < 6; i++) {
          code += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        user.invitationCode = code;
      }
    },
    beforeUpdate: async (user) => {
      // 如果密码被修改，重新加密
      if (user.changed('password')) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    }
  }
});

// 实例方法：验证密码
User.prototype.verifyPassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

  // 关联关系
  User.associate = (models) => {
    // 自关联：邀请关系
    User.belongsTo(User, { as: 'inviter', foreignKey: 'inviterId' });
    User.hasMany(User, { as: 'invitees', foreignKey: 'inviterId' });
    
    // 与订单的关联
    User.hasMany(models.Order, {
      foreignKey: 'userId',
      as: 'orders'
    });
    
    // 与积分交易记录的关联
    User.hasMany(models.PointsTransaction, {
      foreignKey: 'userId',
      as: 'pointsTransactions'
    });
  };

  return User;
};